/*
 * @Author: piaopiao.huang
 * @Date: 2021-12-30 09:37:15
 * @LastEditors: xqm 13697256625@163.com
 * @LastEditTime: 2023-12-29 21:24:51
 * @Description: axios 封装
 */

import axios from 'axios'
import store from '@/store'
import { getToken, getTokenType } from '@/utils/auth'
import { Notify } from 'vant'
import { Toast } from 'vant';
const service = axios.create({
  withCredentials: true,
  timeout: 500000
})

// 请求拦截
service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = getTokenType() + ' ' + getToken();
    config.baseURL = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_NGINX_PATH : localStorage.getItem('baseUrl') + '/factory/v1/jy-api';
    if(config.headers['jun-path'] == '1') {
      config.baseURL = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_JUN_YU_NGINX_PATH : config.baseURL + process.env.VUE_APP_JUN_YU_NGINX_PATH
    }
     //详情页面默认添加主体字段去搜索提交
    if(store.getters.businessUnitCodeDetail && store.getters.businessGroupShow){
      if( config.method== 'post'){
        if( Array.isArray( config.data)){
           if(config.data.length>0 && config.data[0]){
                let typeObj = typeof config.data[0]
                if(typeObj=='object'){//如果请求的参数是数字对象，则都加上业务单元
                  config.data = config.data.map(item=>{return {...item,businessUnitCode:item.businessUnitCode || store.getters.businessUnitCodeDetail} } )
                }
              }
        }else{
           config.data = {...config.data ,businessUnitCode:store.getters.businessUnitCodeDetail } 
               if(config.url.indexOf('?')>-1){
                 config.url += '&businessUnitCode='+store.getters.businessUnitCodeDetail
               }
        }
      }else if(config.method== 'get'){
        config.params = {...config.params ,businessUnitCode:store.getters.businessUnitCodeDetail }
      }
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截
service.interceptors.response.use(
  response => {
    console.log(response,'response')
    if (response.data.code != '200') {

      // if (response.data.code === '3002') {
      //   // 回退到登录页
      // } else if (
      //   response.data.code === '3005' ||
      //   response.data.code === '3007'
      // ) {
      //   // 登录过期 回退到登录页
      // } else {
      //   // 错误提示
      //   // Notify({ type: 'danger', message: response.data.message })
      //   return response
      // }

      Toast.fail(response.data.message)
      return Promise.reject(new Error(response.data.message || 'Error'))
    } else {
      return response
    }
  },
  error => {
    // 错误提示
    return Promise.reject(error)
  }
)

export default service
